// pages/store/edit-store.ts
import { MerchantAPI, UploadAPI } from '../../utils/api'

interface EditStoreForm {
  merchantName: string
  address: string
  latitude: string
  longitude: string
  businessLicense: string
  foodLicense: string
  contactPerson: string
  contactPhone: string
}

interface EditStorePageData {
  statusBarHeight: number
  navHeight: number
  contentPaddingTop: number
  loading: boolean
  submitting: boolean
  formData: EditStoreForm
  businessLicenseUploading: boolean
  foodLicenseUploading: boolean
}

Page({
  data: {
    statusBarHeight: 0,
    navHeight: 0,
    contentPaddingTop: 0,
    loading: false,
    submitting: false,
    businessLicenseUploading: false,
    foodLicenseUploading: false,
    formData: {
      merchantName: '',
      address: '',
      latitude: '',
      longitude: '',
      businessLicense: '',
      foodLicense: '',
      contactPerson: '',
      contactPhone: ''
    }
  } as EditStorePageData,

  onLoad() {
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight || 0
    const navHeight = statusBarHeight + 44
    this.setData({
      statusBarHeight,
      navHeight,
      contentPaddingTop: navHeight + 16
    })
    this.loadStoreInfo()
  },

  async loadStoreInfo() {
    this.setData({ loading: true })

    try {
      const cachedInfo = wx.getStorageSync('merchantUserInfo')
      if (cachedInfo) {
        this.applyStoreInfo(cachedInfo)
      }

      const response = await MerchantAPI.getMerchantInfo()
      if (response.code === 200 && response.data) {
        this.applyStoreInfo(response.data)
        wx.setStorageSync('merchantUserInfo', response.data)
      }
    } catch (error) {
      console.error('加载门店信息失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  applyStoreInfo(data: any) {
    this.setData({
      formData: {
        merchantName: data.merchantName || '',
        address: data.address || '',
        latitude: data.latitude != null ? String(data.latitude) : '',
        longitude: data.longitude != null ? String(data.longitude) : '',
        businessLicense: data.businessLicense || '',
        foodLicense: data.foodLicense || '',
        contactPerson: data.contactPerson || '',
        contactPhone: data.contactPhone || ''
      }
    })
  },

  onInputChange(e: any) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value || ''

    if (field === 'contactPhone') {
      wx.showToast({
        title: '手机号请前往个人中心修改',
        icon: 'none'
      })
      return
    }

    this.setData({
      [`formData.${field}`]: value
    })
  },

  chooseLocation() {
    wx.chooseLocation({
      success: (res) => {
        this.setData({
          'formData.address': res.address || res.name || '',
          'formData.latitude': res.latitude != null ? res.latitude.toFixed(6) : '',
          'formData.longitude': res.longitude != null ? res.longitude.toFixed(6) : ''
        })
      },
      fail: (error) => {
        if (error.errMsg?.includes('cancel')) {
          return
        }
        console.error('选择地址失败:', error)
        wx.showToast({
          title: '选择地址失败',
          icon: 'none'
        })
      }
    })
  },

  async handleUpload(e: any) {
    const fileType = e.currentTarget.dataset.type as 'businessLicense' | 'foodLicense'

    if (!fileType) {
      return
    }

    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const tempFilePath = res.tempFilePaths[0]

        if (fileType === 'businessLicense') {
          this.setData({ businessLicenseUploading: true })
        } else {
          this.setData({ foodLicenseUploading: true })
        }

        wx.showLoading({
          title: '上传中...',
          mask: true
        })

        try {
          const uploadRes = await UploadAPI.uploadFile(tempFilePath)
          console.log('店铺资质上传响应:', uploadRes);
          if (uploadRes.code === 200) {
            // 后端返回格式: { code: 200, msg: "操作成功", data: "https://xxx.com/xxx.png" }
            let url = '';
            if (uploadRes.data) {
              if (typeof uploadRes.data === 'string') {
                url = uploadRes.data;
              } else if (uploadRes.data.url) {
                url = uploadRes.data.url;
              } else if (uploadRes.data.fileUrl) {
                url = uploadRes.data.fileUrl;
              } else if (uploadRes.data.filePath) {
                url = uploadRes.data.filePath;
              }
            }
            if (!url) {
              url = uploadRes.url || uploadRes.fileUrl || uploadRes.filePath || tempFilePath;
            }
            console.log('店铺资质最终URL:', url);

            this.setData({
              [`formData.${fileType}`]: url
            })

            wx.showToast({
              title: '上传成功',
              icon: 'success'
            })
          } else {
            wx.showToast({
              title: uploadRes.msg || '上传失败',
              icon: 'none'
            })
          }
        } catch (error) {
          console.error('上传资质失败:', error)
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          })
        } finally {
          wx.hideLoading()
          if (fileType === 'businessLicense') {
            this.setData({ businessLicenseUploading: false })
          } else {
            this.setData({ foodLicenseUploading: false })
          }
        }
      }
    })
  },

  previewImage(e: any) {
    const url = e.currentTarget.dataset.url
    if (!url) {
      return
    }

    wx.previewImage({
      urls: [url],
      current: url
    })
  },

  validateForm(): boolean {
    const { merchantName, address, latitude, longitude } = this.data.formData

    if (!merchantName.trim()) {
      wx.showToast({
        title: '请输入门店名称',
        icon: 'none'
      })
      return false
    }

    if (!address.trim()) {
      wx.showToast({
        title: '请输入门店地址',
        icon: 'none'
      })
      return false
    }

    const lat = parseFloat(latitude)
    const lng = parseFloat(longitude)

    if (isNaN(lat) || isNaN(lng)) {
      wx.showToast({
        title: '请先选择门店位置',
        icon: 'none'
      })
      return false
    }

    return true
  },

  async submitForm() {
    if (this.data.submitting) {
      return
    }

    if (!this.validateForm()) {
      return
    }

    const { formData } = this.data

    const payload: any = {
      merchantName: formData.merchantName.trim(),
      address: formData.address.trim(),
      latitude: Number(formData.latitude),
      longitude: Number(formData.longitude),
      businessLicense: formData.businessLicense || '',
      foodLicense: formData.foodLicense || ''
    }

    if (formData.contactPerson && formData.contactPerson.trim()) {
      payload.contactPerson = formData.contactPerson.trim()
    }

    this.setData({ submitting: true })
    wx.showLoading({ title: '保存中...', mask: true })

    try {
      const response = await MerchantAPI.updateStoreInfo(payload)
      if (response.code === 200) {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })

        const cachedInfo = wx.getStorageSync('merchantUserInfo') || {}
        cachedInfo.merchantName = payload.merchantName
        cachedInfo.address = payload.address
        cachedInfo.latitude = payload.latitude
        cachedInfo.longitude = payload.longitude
        cachedInfo.businessLicense = payload.businessLicense
        cachedInfo.foodLicense = payload.foodLicense
        if (payload.contactPerson !== undefined) {
          cachedInfo.contactPerson = payload.contactPerson
        }
        wx.setStorageSync('merchantUserInfo', cachedInfo)

        setTimeout(() => {
          const pages = getCurrentPages()
          const prevPage = pages[pages.length - 2]
          if (prevPage && typeof prevPage.loadMerchantInfo === 'function') {
            prevPage.loadMerchantInfo()
          }
          wx.navigateBack({ delta: 1 })
        }, 800)
      } else {
        wx.showToast({
          title: response.msg || '保存失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('保存门店信息失败:', error)
      wx.showToast({
        title: '保存失败，请稍后重试',
        icon: 'none'
      })
    } finally {
      this.setData({ submitting: false })
      wx.hideLoading()
    }
  },

  goBack() {
    wx.navigateBack({ delta: 1 })
  }
})

